package com.alibaba.algo.apiimpl.user;

import com.alibaba.algo.annotation.OperateLogAnnotation;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.service.SysCarouselFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.SysCarouselRequestVO;
import com.alibaba.algo.cooperation.feign.vo.req.SysFileRequestVO;
import com.alibaba.algo.cooperation.feign.vo.res.SysCarouselResponseVO;
import com.alibaba.algo.cooperation.feign.vo.res.SysFileResponseVO;
import com.alibaba.algo.domain.user.SysCarouselDomain;
import com.alibaba.algo.domain.user.SysFileDomain;
import com.alibaba.algo.entity.user.SysCarousel;
import com.alibaba.algo.entity.user.SysFile;
import com.alibaba.algo.enums.OperateTypeEnum;
import com.alibaba.algo.enums.ResourceTypeEnum;
import com.alibaba.algo.utils.FileUtils;
import com.alibaba.algo.utils.JedisUtil;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 类SysCarouselImpl.java的实现描述：用户系统轮播图表 serviceimpl
 *
 */
@Slf4j
@RestController
public class SysCarouselServiceImpl implements SysCarouselFeignService {

    @Autowired
    private SysCarouselDomain sysCarouselDomain;

    @Autowired
    private SysFileDomain sysFileDomain;


    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.CAROUSEL,operateType = OperateTypeEnum.INSERT)
    public BaseResult insert(SysCarouselRequestVO vo) {
        SysCarousel sysCarousel = new SysCarousel();
        BeanUtils.copyProperties(vo, sysCarousel);
        //拼装carouselIds
        List<Long> idList = vo.getCarouselIdList();
        String ids = null;
        if(!ObjectUtils.isEmpty(idList)){
            StringBuilder idsStrBuiler = new StringBuilder();
            for(Long id : idList){
                idsStrBuiler.append(id.toString()).append(",");
            }
            ids = idsStrBuiler.substring(0,idsStrBuiler.length()-1);
        }
        sysCarousel.setCarouselIds(ids);
        Integer result = sysCarouselDomain.insert(sysCarousel);
        if(!ObjectUtils.isEmpty(result) && result > 0){
            return BaseResult.buildSuccess("新增系统登录配置信息成功");
        }else{
            return BaseResult.buildError("新增系统登录配置信息失败");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.CAROUSEL,operateType = OperateTypeEnum.UPDATE)
    public BaseResult update(SysCarouselRequestVO vo) {
        SysCarousel sysCarousel = new SysCarousel();
        BeanUtils.copyProperties(vo, sysCarousel);
        //拼装carouselIds
        List<Long> idList = vo.getCarouselIdList();
        String ids = null;
        if(!ObjectUtils.isEmpty(idList)){
            StringBuilder idsStrBuiler = new StringBuilder();
            for(Long id : idList){
                idsStrBuiler.append(id.toString()).append(",");
            }
            ids = idsStrBuiler.substring(0,idsStrBuiler.length()-1);
        }
        sysCarousel.setCarouselIds(ids);
        Integer result = sysCarouselDomain.updateById(sysCarousel);
        if(!ObjectUtils.isEmpty(result) && result > 0){
            return BaseResult.buildSuccess("更新系统登录配置信息成功");
        }else{
            return BaseResult.buildError("更新系统登录配置信息失败");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public SysCarouselResponseVO selectOne() {
        SysCarousel sysCarousel = sysCarouselDomain.getSysCarousel();
        SysCarouselResponseVO sysCarouselResponseVO = new SysCarouselResponseVO();
        //查询logo信息
        if(!ObjectUtils.isEmpty(sysCarousel.getLogoId())){
            //从redis中获取
            String logoSysFileStr = JedisUtil.getStringValue(Constants.SYS_FILE_CACHE_PREFIX+sysCarousel.getLogoId().toString());
            if(StringUtils.isNotEmpty(logoSysFileStr)){
                SysFile logoSysFile = JSON.parseObject(logoSysFileStr,SysFile.class);
                if(null != logoSysFile){
                    sysCarouselResponseVO.setLogoId(logoSysFile.getId());
                    sysCarouselResponseVO.setLogoName(logoSysFile.getFileName());
                    sysCarouselResponseVO.setLogoSuffix(logoSysFile.getFileSuffix());
                    sysCarouselResponseVO.setLogoBase64(logoSysFile.getFileBase64());
                }
            }else{//从数据库获取
                sysCarouselResponseVO = sysFileDomain.getSysFileById(sysCarousel.getLogoId());
                //同时放入redis
                SysFile logoSysFileForCache = new SysFile();
                logoSysFileForCache.setId(sysCarousel.getLogoId());
                logoSysFileForCache.setFileName(sysCarouselResponseVO.getLogoName());
                logoSysFileForCache.setFileSuffix(sysCarouselResponseVO.getLogoSuffix());
                logoSysFileForCache.setFileBase64(sysCarouselResponseVO.getLogoBase64());
                logoSysFileForCache.setFileType(Constants.SYS_FILE_TYPE_LOGO);
                JedisUtil.setStringValue(Constants.SYS_FILE_CACHE_PREFIX+sysCarousel.getLogoId().toString(), JSON.toJSONString(logoSysFileForCache),FileUtils.getFileExpireTime());
            }
        }
        BeanUtils.copyProperties(sysCarousel, sysCarouselResponseVO);
        //查询轮播图信息
        List<SysFileResponseVO> sysFileResponseVOList = new ArrayList<>();
        if(!ObjectUtils.isEmpty(sysCarousel.getCarouselIds())){
            List<Long> ids = new ArrayList<>();
            if(sysCarousel.getCarouselIds().contains(",")){
                String[] idStrArray = sysCarousel.getCarouselIds().split(",");
                for(int i=0;i<idStrArray.length;i++){
                    ids.add(Long.parseLong(idStrArray[i]));
                }
            }else{
                ids.add(Long.parseLong(sysCarousel.getCarouselIds()));
            }
            Iterator<Long> iterator = ids.iterator();
            while(iterator.hasNext()){
                Long sysFileId = iterator.next();
                if(null != sysFileId && sysFileId >= 0){
                    String sysFileStr = JedisUtil.getStringValue(Constants.SYS_FILE_CACHE_PREFIX+sysFileId.toString());
                    if(StringUtils.isNotEmpty(sysFileStr)){
                        SysFile sysFile = JSON.parseObject(sysFileStr,SysFile.class);
                        if(null != sysFile){
                            SysFileResponseVO sysFileResponseVO = new SysFileResponseVO();
                            BeanUtils.copyProperties(sysFile, sysFileResponseVO);
                            sysFileResponseVOList.add(sysFileResponseVO);
                            iterator.remove();
                        }
                    }
                }
            }
            if(null != ids && !ids.isEmpty()){//redis中未获取到，从数据库获取
                List<SysFileResponseVO> sysFileList = sysFileDomain.getListByIds(ids,Constants.SYS_FILE_TYPE_CAROUSEL);
                if(!ObjectUtils.isEmpty(sysFileList)){
                    for(SysFileResponseVO sysFileResponseVO : sysFileList){
                        sysFileResponseVOList.add(sysFileResponseVO);
                        //同时放入redis
                        SysFile sysFileForCache = new SysFile();
                        BeanUtils.copyProperties(sysFileResponseVO, sysFileForCache);
                        sysFileForCache.setFileType(Constants.SYS_FILE_TYPE_CAROUSEL);
                        JedisUtil.setStringValue(Constants.SYS_FILE_CACHE_PREFIX+sysFileForCache.getId().toString(), JSON.toJSONString(sysFileForCache),FileUtils.getFileExpireTime());
                    }
                }
            }
        }
        sysCarouselResponseVO.setCarouselList(sysFileResponseVOList);
        return sysCarouselResponseVO;
    }

    @Override
    public BaseResult uploadFile(SysFileRequestVO sysFileRequestVO) {
        if (!ObjectUtils.isEmpty(sysFileRequestVO)){
            SysFile sysFile = new SysFile();
            BeanUtils.copyProperties(sysFileRequestVO, sysFile);
            sysFileDomain.insert(sysFile);
            //存数据库的同时 放入redis
            if(null != sysFile.getId() && sysFile.getId() >= 0){
                JedisUtil.setStringValue(Constants.SYS_FILE_CACHE_PREFIX+sysFile.getId().toString(), JSON.toJSONString(sysFile),FileUtils.getFileExpireTime());
            }
            return BaseResult.buildSuccess(sysFile.getId());
        }else{
            return BaseResult.buildError("上传系统图片失败");
        }
    }

}
